// utils.js
import chalk from 'chalk';
import fs from 'fs-extra'
import ora from 'ora'
import path from 'path'
import inquirer from 'inquirer'
import shell from 'shelljs'
const appDirectory = fs.realpathSync(process.cwd()); //process.cwd() 方法返回 Node.js 进程的当前工作目录 appDirectory
const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath); //path.resolve() relativePath方法将路径或路径片段的序列解析为绝对路径。

export function isUnicodeSupported() {
  // 操作系统平台是否为 win32（Windows）
  if (process.platform !== "win32") {
    // 判断 process.env.TERM 是否为 'linux'，
    // 这表示在 Linux 控制台（内核）环境中。
    return process.env.TERM !== "linux"; // Linux console (kernel)
  }

  return (
    Boolean(process.env.CI) || // 是否在持续集成环境中
    Boolean(process.env.WT_SESSION) || // Windows 终端环境（Windows Terminal）中的会话标识
    Boolean(process.env.TERMINUS_SUBLIME) || // Terminus 插件标识
    process.env.ConEmuTask === "{cmd::Cmder}" || // ConEmu 和 cmder 终端中的任务标识
    process.env.TERM_PROGRAM === "Terminus-Sublime" ||
    process.env.TERM_PROGRAM === "vscode" || // 终端程序的标识，可能是 'Terminus-Sublime' 或 'vscode'
    process.env.TERM === "xterm-256color" ||
    process.env.TERM === "alacritty" || // 终端类型，可能是 'xterm-256color' 或 'alacritty'
    process.env.TERMINAL_EMULATOR === "JetBrains-JediTerm" // 终端仿真器的标识，可能是 'JetBrains-JediTerm'
  );
}


//删除文件夹
export async function deleteFolder(folderPath) {
  const spinner = ora({

  tetx:`Deleting folder 正在删除: ${folderPath}`,
  color: 'yellow'

  }).start();
  // console.log(resolveApp(folderPath))
  
  try {
   
    await fs.remove(resolveApp(folderPath));
    console.log(`Deleted folder: ${folderPath}`);
    spinner.succeed(chalk.greenBright(`Deleted folder: ${chalk.cyan(folderPath)}`));
  } catch (error) {
    spinner.fail(chalk.redBright(`Failed to delete folder: ${chalk.cyan(folderPath)}`
      
      )
    )
    console.error(`Error deleting folder: ${error}`);
  }
}

//修改拉取的package.json文件参数
export async function modifyPackageJson(name, info) {
  const pkg = await fs.readJson(resolveApp(`${name}/package.json`));
  Object.keys(info).forEach((item) => {
    if (item === "name") {
      pkg[item] = info[item] && info[item].trim() ? info[item].trim() : name;
    } else if (item === "keywords" && info[item] && info[item].trim()) {
      pkg[item] = info[item].split(",");
    } else if (info[item] && info[item].trim()) {
      pkg[item] = info[item];
    }
  });
  await fs.writeJson(resolveApp(`${name}/package.json`), pkg, { spaces: 2 });
}

/**
 * @param {Array} messages  询问提示语句数组
 * @returns {Object} 结果对象
 */
export const inquirerInputs = async (messages) => { 
  const answers = await inquirer.prompt(messages.map(msg => { 
    return {
      name: msg.name,
      type: "input",
      message: msg.message,
    }
  }));
  return answers
}

// 执行npm的拉取
export async function npmInstall(name) {
  const spinner = ora({
    text: `Installing dependencies 正在安装依赖: ${name}`,
    color: 'yellow'
  }).start();
  // try {
  //   // await execa('npm', ['install'], {
  //   //   cwd: resolveApp(name),        
  //   //   stdio: 'inherit',

  //   // });
   
  // }
  // catch (error) {
  //   spinner.fail(chalk.redBright(`Failed to install dependencies: ${chalk.cyan(name)}`));
  //   console.error(`Error installing dependencies: ${error}`);
  // }
  if (
    shell.exec(`cd ${shell.pwd()}/${name} && pnpm install --force -d`).code !== 0
  ) {
    console.log(
      logSymbols.error,
      chalk.yellowBright("对不起,依赖安装失败,请手动安装")
    );
    shell.exit(1);
  }
  spinner.succeed(chalk.greenBright("~~~依赖安装成功~~~"));
  spinner.succeed(chalk.greenBright("~~~项目创建完成~~~"));

  shell.exit(1);
}